package com.xiaoai.httpClientTestService.httpclient.myown;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Httpclient1 {
    
    public static void main(String[] args) throws IOException, ParseException {

        //获取一个客户端
        CloseableHttpClient aDefault = HttpClients.createDefault();

        //定义请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                //连接超时时间
                .setConnectTimeout(30, TimeUnit.SECONDS)
                //连接请求超时时间
                .setConnectionRequestTimeout(10,TimeUnit.SECONDS)
                //响应超时时间
                .setResponseTimeout(10,TimeUnit.SECONDS)
                .build();

        /**
         * Get请求
         */
//        HttpGet httpGet = new HttpGet("http://localhost:8080/hello");
//        httpGet.setConfig(requestConfig);
//
//        CloseableHttpResponse response = aDefault.execute(httpGet);
//
//        System.out.println("响应码："+response.getCode());
//
//        HttpEntity entity = response.getEntity();
//        System.out.println("实体"+ entity);
//
//        String s = EntityUtils.toString(entity);
//        System.out.println(s);

        /**
         * Post请求
         */
//        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getp");
        HttpPost httpPost = new HttpPost("http://localhost:8080/hello");
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type","application/json");

        //发送请求
        CloseableHttpResponse response = aDefault.execute(httpPost);

        System.out.println("响应码："+response.getCode());

        HttpEntity entity = response.getEntity();
        System.out.println("实体"+ entity);

        String s = EntityUtils.toString(entity);
        System.out.println(s);

    }
    
    
}
